<template>
    <el-dialog
        v-model="dialogVisible"
        @close="closeDialog"
        :close-on-click-modal="false"
        title="会员等级高级设置"
        width="640px"
    >
        <div v-loading="showLoading" element-loading-background="rgba(0,0,0,0)">
            <el-form
                :style="{opacity: showLoading ? 0 : 1}"
                class="mr8 mt10"
                label-width="180"
                ref="ruleFormRef"
                :rules="rules"
                :model="ruleForm"
            >
                <el-form-item label="小程序会员权益展示页" prop="customize_benefits" :required="isCustomizeBenefits">
                    <div>
                        <el-radio-group v-model="ruleForm.customizeBenefits" @change="radioChangeBenefits">
                            <el-radio :value="1">默认配置</el-radio>
                            <el-radio :value="2">自定义配置</el-radio>
                        </el-radio-group>
                        <el-form-item v-if="isCustomizeBenefits">
                            <div style="width: 78px;height: 78px;border: 1px solid #FFFFFF;"/>
                        </el-form-item>
                        <p class="form-tip-color fz11">*建议尺寸：宽度750dpi，高度不限制，图片大小不超过2M，支持jpg, jpeg, png格式</p>
                    </div>
                </el-form-item>
                <el-form-item label="等级进度条">
                    <div>
                        <el-radio-group v-model="ruleForm.level_progress_bar">
                            <el-radio :value="2">不展示</el-radio>
                            <el-radio :value="1">展示</el-radio>
                        </el-radio-group>
                        <p class="form-tip-color fz11 line-h18">小程序端是否展示会员等级升级进度</p>
                    </div>
                </el-form-item>
                <el-form-item label="升级条件超出部分">
                    <div>
                        <el-radio-group v-model="ruleForm.level_upgrade_the_excess">
                            <el-radio :value="2">不计入</el-radio>
                            <el-radio :value="1">计入</el-radio>
                        </el-radio-group>
                        <p class="form-tip-color fz11 line-h18">会员等级升级条件超出部分是否计入下一级</p>
                    </div>
                </el-form-item>
                <el-form-item label="消费送多倍积分">
                    <div>
                        <el-radio-group v-model="ruleForm.level_multiple_point">
                            <el-radio :value="1">倍数相乘</el-radio>
                            <el-radio :value="2">以最大倍数计算</el-radio>
                        </el-radio-group>
                        <p class="form-tip-color fz11 line-h18">指消费送多倍积分场景出现在同一天时倍数计算依据</p>
                    </div>
                </el-form-item>
                <el-form-item label="等级礼跨级赠送">
                    <div>
                        <el-radio-group v-model="ruleForm.through_level_gifts">
                            <el-radio :value="2">不赠送</el-radio>
                            <el-radio :value="1">赠送</el-radio>
                        </el-radio-group>
                        <p class="form-tip-color fz11 line-h18">会员因从Lv.n直接升级到Lv.n+2，是否赠送Lv.n+1的等级优惠券礼</p>
                    </div>
                </el-form-item>
                <el-form-item label="等级礼降级后再次升级赠送">
                    <div>
                        <el-radio-group v-model="ruleForm.level_downgrade_and_upgrade">
                            <el-radio :value="2">不赠送</el-radio>
                            <el-radio :value="1">赠送</el-radio>
                        </el-radio-group>
                        <p class="form-tip-color fz11 line-h18">会员降级后再次升级，是否赠送升级的等级礼</p>
                    </div>
                </el-form-item>
                <el-form-item label="注册或升级赠送的积分">
                    <div>
                        <el-radio-group v-model="ruleForm.register_and_level_point">
                            <el-radio :value="2">不计入</el-radio>
                            <el-radio :value="1">计入</el-radio>
                        </el-radio-group>
                        <p class="form-tip-color fz11 line-h18">注册或升级获得的积分是否计入升级条件</p>
                    </div>
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
            <el-button :loading="subLoading" :disabled="subLoading" class="mr8" type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
    import { computed, nextTick, PropType, reactive, ref, watch } from "vue";
    import { _mallStore } from "@/store/config"
    import { putRestfulMallConfig } from "@/assets/api";
    import { ElMessage } from "element-plus";

    const props = defineProps({
        modelValue: {
            type: Boolean,
            default: false,
        },
        detail: {
            type: Object as PropType<ObjValueAny>,
            default: () => {
                return {}
            }
        },
    })

    const emit = defineEmits(['update:modelValue', 'change']);
    let dialogVisible = ref<boolean>(false);// 显示弹窗
    // 关闭弹窗
    const closeDialog = () => {
        cancelDialog();
        emit('update:modelValue', dialogVisible.value);
    }
    // 关闭弹窗
    const cancelDialog = () => {
        dialogVisible.value = false;
    }

    const submitData: ObjValueAny = {
        customize_benefits: '',// 会员权益图片
        level_progress_bar: 2, // 等级进度条 1开启 2关闭
        level_upgrade_the_excess: 2,// 升级条件超出部分 1. 计入下次升级 2不计入下次升级
        level_multiple_point: 2,// 消费送多倍积分 1.倍数相乘 2以最大倍数计算
        through_level_gifts: 2,// 等级礼跨级赠送 1.赠送 2不赠送
        level_downgrade_and_upgrade: 2,// 降级后再升级  1.赠送礼品 2不赠送礼品
        register_and_level_point: 2,// 注册和等级积分计入等级升级 1.计入升级积分 2.不计入
    }
    let ruleForm = reactive<ObjValueAny>({
        customizeBenefits: 1,
        ...submitData,
    });

    // 小程序会员权益展示页 自定义配置
    const isCustomizeBenefits = computed(() => {
        return ruleForm.customizeBenefits === 2;
    })

    const radioChangeBenefits = () => {
        ruleForm.customize_benefits = '';
        if (isCustomizeBenefits.value) {
            nextTick(() => {
                ruleFormRef.value.validateField('customize_benefits', () => {
                })
            })
        }
    }

    // 小程序会员权益展示页 验证
    const validatorCustomizeBenefits = (rule: ObjValueAny, value: string, callback: Function) => {
        if (subStatus && isCustomizeBenefits.value) {
            if (!value) {
                return callback(new Error('请选择优惠券'));
            }
        }
        callback()
    }

    const rules = reactive<ObjValueAny>({
        customize_benefits: [{ required: true, validator: validatorCustomizeBenefits, trigger: 'change' }],
    });

    const ruleFormRef = ref();
    let subStatus: boolean = false;
    // 表单验证
    const submitForm = async (formEl: any) => {
        subStatus = true;
        if (!formEl) return;
        await formEl.validate((valid: boolean, fields: ObjValueAny) => {
            if (valid) {
                console.log('submit!');
                onSave();
            } else {
                console.log('error submit!', fields)
            }
        });
    }

    let onSaveStatus = ref<boolean>(false);
    const onSave = () => {
        onSaveStatus.value = true;
        const miniapp: ObjValueAny = {};
        for (let key in submitData) {
            miniapp[key] = ruleForm[key];
        }
        ElMessage.closeAll();
        ElMessage({
            showClose: true,
            message: '保存中...',
            type: 'success',
            duration: 0,
        });
        putRestfulMallConfig({ config: { miniapp } }, { noRepeat: 1 }).then((resp: ObjValueAny) => {
            ElMessage.closeAll();
            if (resp.code === 200) {
                ElMessage.success('保存成功');
                resetForm(ruleFormRef.value);
            } else {
                ElMessage.error(resp.msg);
                onSaveStatus.value = false;
            }
        }).catch(() => {
            ElMessage.closeAll();
            onSaveStatus.value = false;
        })
    }

    const resetForm = (formEl: any) => {
        if (!formEl) return
        cancelDialog();
        formEl.resetFields()
    }

    let showLoading = ref<boolean>(true);
    const subLoading = computed(() => {
        return showLoading.value || onSaveStatus.value;
    })
    watch(() => props.modelValue, async (bool: boolean) => {
        dialogVisible.value = bool;
        subStatus = false;
        if (bool) {
            onSaveStatus.value = false;
            showLoading.value = true;
            await _mallStore.getZeusMallConfigStore();
            const miniApp: ObjValueAny = _mallStore.mallZeusConfig?.miniapp || {};
            for (let key in submitData) {
                ruleForm[key] = miniApp[key] || submitData[key];
            }
            ruleForm.customizeBenefits = !!miniApp.customize_benefits ? 2 : 1;
            showLoading.value = false;
        }
    })
</script>